package com.sr.controller.api;

import com.sr.annotation.ApiAuth;
import com.sr.constant.Constant;
import com.sr.controller.BaseController;
import com.sr.enums.ResponseCode;
import com.sr.pojo.WMember;
import com.sr.service.IMemberService;
import com.sr.util.BCrypt;
import com.sr.util.R;
import com.sr.vo.req.MemberReqVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xiaochi
 * @date 2022/4/27 18:39
 * @desc MemberControllerApi
 */
@Api(tags = "会员模块")
@RestController
@RequestMapping(Constant.Api.WEB_PREFIX+"/member")
@RequiredArgsConstructor(onConstructor = @__)
public class MemberControllerApi extends BaseController{

    private final IMemberService memberService;

    /**
     * 注册会员
     * @return
     */
    @ApiOperation(value = "注册会员",notes = "注册会员")
    @PostMapping("/create")
    public R<String> create(@RequestBody @Validated(MemberReqVo.Create.class) MemberReqVo reqVo){
        if (memberService.hasExistsByName(reqVo)){
            return R.error(ResponseCode.ACCOUNT_EXISTS_ERROR.getMessage());
        }
        WMember wMember = reqVo.buildEntity();
        wMember.setPassword(BCrypt.hashpw(wMember.getPassword(),BCrypt.gensalt()));
        return this.response(memberService.insert(wMember));
    }

    /**
     * 更新会员
     * @return
     */
    @ApiOperation(value = "更新会员",notes = "更新会员")
    @ApiAuth
    @PostMapping("/update")
    public R<String> update(@RequestBody @Validated(MemberReqVo.Update.class) MemberReqVo reqVo){
        if (memberService.hasExistsByName(reqVo)){
            return R.error(ResponseCode.ACCOUNT_EXISTS_ERROR.getMessage());
        }
        return this.response(memberService.updateById(reqVo.buildEntity()));
    }
}